package logic

import (
	"context"
	"errors"
	"person/models/mysql"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *personrpc.RegisterRequest) (*personrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindUserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("用户已存在，请重新注册")
	}
	users := &mysql.User{
		Mobile:   in.Mobile,
		Password: in.Password,
	}
	if err := users.UserRegister(mysql.DB); err != nil {
		return nil, errors.New("注册失败")
	}
	return &personrpc.RegisterResponse{
		UserId: int64(users.ID),
	}, nil
}
